import numpy as np
from keras.models import model_from_json
from keras.preprocessing import image
import cv2
#忽略tensorflow错误的警告（因为我这环境的tf是用pip安装，不是源码安装）
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
#加载模型
with open('fer.json','r') as file:
    model_json=file.read()
new_model=model_from_json(model_json)
#加载权重文件
new_model.load_weights('fer.h5')
#加载cv模型
face_cascade=cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
# 打开摄像头
cap = cv2.VideoCapture(0)
while True:
    ret, fname = cap.read()
    if not ret:
        break
    #读取的人像转换灰度图
    gray = cv2.cvtColor(fname, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray)
    for (x, y, w, h) in faces:
        #定义框框的位置以及颜色
        cv2.rectangle(fname, (x, y), (x + w, y + h), (0, 255, 0), 3)
        roi_gray = gray[y:y + h, x:x + w]
        roi_gray = cv2.resize(roi_gray, (48, 48))
        # 把读取到的图片转换为数组及重新定义维度和归一化
        pixels = image.img_to_array(roi_gray)
        pixels = np.expand_dims(pixels, axis=0)
        pixels /= 255
        # 预测
        pred = new_model.predict(pixels)
        max_index = np.argmax(pred[0])
        emotion = ('angry', 'disgust', 'fear', 'happy', 'sad', 'surprise', 'neutral')
        pred_emotions = emotion[max_index]
    #预测的结果显示出来
        cv2.putText(fname, pred_emotions, (int(x), int(y)), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2)
    resize_fname = cv2.resize(fname, (800, 600))
    cv2.imshow('fname', resize_fname)
    if cv2.waitKey(1) == ord('q'):
        break
cap.release()
cv2.destroyAllWindows()